<template>
  <div ref="ChartLineMetricRef" v-loading="rqLoading" element-loading-text="正在查询流量信息, 请稍后..." :style="{
    'height': fixedBox.height,
    'width': fixedBox.width
  }"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, inject } from 'vue';
import { metricLineRestfulApi } from '@/api/sentinel';
// echarts
import * as echartTheme from '@/assets/styles/xz/echartTheme';
import * as echarts from 'echarts/core';
import { TitleComponent, TooltipComponent, GridComponent, LegendComponent, DataZoomComponent } from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
echarts.use([TitleComponent, TooltipComponent, LegendComponent, DataZoomComponent, GridComponent, LegendComponent, LineChart, CanvasRenderer, UniversalTransition]);

/* ============================================================
 * inject
 * 用于多层嵌套中使用流量, 下列相关信息使用
 * ============================================================ */
const currentMachine: any = inject('currentMachine');
const fixedBox: any = inject('chartLineResourceFixedBox', { height: '100%', width: '100%' });

/* ============================================================
 * props
 * 在单层嵌套中使用的简单的参数
 * ============================================================ */
const props = defineProps({
  resource: { type: String, default: '__total_inbound_traffic__' },
  interval: { type: String, default: '1d' },
  startTime: { type: String, default: '' },
  endTime: { type: String, default: '' },
  // ES 使用的查询参数
  // enum: seconds, minutes, hours, days
  customIntervalUnit: { type: String, default: '' },
  customInterval: { type: Number, default: 0 },
})

// -------------------- ref
const rqLoading = ref<boolean>(true);
const ChartLineMetricRef = ref<any>(null);
let chartLineMetric: any;
let chartData = {
  title: '',
  subTitle: '',
  x: <any>[],// 折线图的X轴
  success: <any>[],
  exception: <any>[],
  pass: <any>[],
  block: <any>[],
  avgRt: <any>[],
  maxVisual: 0
}

// -------------------- methods
/**
 * 查询指标数据
 */
const getChartLineMetric = () => {
  rqLoading.value = true;
  let params = {
    appName: currentMachine.value.appName,
    resource: props.resource,
    interval: props.interval,
    startTime: props.startTime,
    endTime: props.endTime,
    // ES 有的查询参数
    customIntervalUnit: props.customIntervalUnit,
    customInterval: props.customInterval
  }
  metricLineRestfulApi(currentMachine.value.appName, params).then(resp => {
    chartData.title = resp.data.title;
    chartData.subTitle = resp.data.subTitle;
    chartData.x = [];
    chartData.success = [];
    chartData.exception = [];
    chartData.pass = [];
    chartData.block = [];
    chartData.avgRt = [];
    chartData.x = resp.data.x;
    chartData.success = resp.data.s;
    chartData.exception = resp.data.e;
    chartData.pass = resp.data.p;
    chartData.block = resp.data.b;
    chartData.avgRt = resp.data.avgRt;
    renderChart(() => {
      setTimeout(() => {
        rqLoading.value = false;
      }, 150);
    });
  })
}

const renderChart = (callback?: any) => {
  chartLineMetric.setOption({
    title: {
      top: 30, right: 5, text: chartData.title, subtext: chartData.subTitle,
      subtextStyle: { lineHeight: 18 },
      textStyle: echartTheme.title().textStyle
    },
    legend: echartTheme.legend(),
    grid: { top: 30, left: 40, right: 15, bottom: 35 },
    xAxis: { type: 'category', data: chartData.x, nameRotate: 15 },
    yAxis: { splitLine: { lineStyle: { color: echartTheme.common().axisLineColor } } },
    tooltip: echartTheme.tooltip(),
    dataZoom: [
      { type: 'inside' },
      {
        ...echartTheme.dataZoom(), ...{
          type: 'slider',
          width: 200, height: 15,
          top: 5,
          start: 50, end: 100,
        }
      }
    ],
    series: [
      {
        type: 'line',
        name: 'Success',
        sampling: 'lttb',
        smooth: false, // 平滑曲线
        showSymbol: false,
        data: chartData.success,
        lineStyle: { width: 2 },
        areaStyle: {
          color: {
            type: 'linear', x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [{ offset: 0, color: '#0066FF' }, { offset: 1, color: '#0066FF00' }]
          }
        }
      },
      {
        type: 'line',
        name: 'Exception',
        sampling: 'lttb',
        smooth: false, // 平滑曲线
        showSymbol: false,
        data: chartData.exception,
        lineStyle: { color: echartTheme.clr().red, width: 1 },
        itemStyle: { color: echartTheme.clr().red }
      },
      {
        type: 'line',
        name: 'Block',
        sampling: 'lttb',
        smooth: false, // 平滑曲线
        showSymbol: false,
        data: chartData.block,
        lineStyle: { color: echartTheme.clr().yellow, width: 1 },
        itemStyle: { color: echartTheme.clr().yellow }
      },
      {
        z: 2,
        type: 'line',
        name: 'RT',
        sampling: 'lttb',
        smooth: false, // 平滑曲线
        showSymbol: false,
        data: chartData.avgRt,
        lineStyle: { color: echartTheme.clr().purple, width: 1 },
        itemStyle: { color: echartTheme.clr().purple },
        areaStyle: {}
      },
    ]
  });
  if (callback !== undefined) {
    callback();
  }
}

const reload = () => {
  nextTick(() => {
    getChartLineMetric();
  })
}

const windowResize = () => {
  chartLineMetric.resize();
}

onMounted(() => {
  chartLineMetric = echarts.init(ChartLineMetricRef.value);
  windowResize();
})

defineExpose({
  reload, windowResize
})
</script>

<style scoped lang="scss">
.chart-resource-histogram-root {
  @include box(100%, 100%);
}
</style>